package service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;

import common.impl.FileHandleImpl;
import common.impl.exception.ServiceException;

import model.MTest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.interf.ITest;

import dao.interf.*;
import dao.pojo.*;


public class TestImpl implements ITest {
	private ITestDao testDao;
	private IListenDao listenDao;
	private ISelectionDao selectionDao;
	private ITranslateDao translateDao;
	private IRewriteDao rewriteDao;
	private IReadingDao readDao;
	private IWritingDao writeDao;
	private IPassageDao passageDao;
	private ITeacherDao teacherDao;
	
	public void setTeacherDao(ITeacherDao teacherDao) {
		this.teacherDao = teacherDao;
	}
	
	public void setTestDao(ITestDao testDao) {
		this.testDao = testDao;
	}

	public void setListenDao(IListenDao listenDao) {
		this.listenDao = listenDao;
	}

	public void setSelectionDao(ISelectionDao selectionDao) {
		this.selectionDao = selectionDao;
	}

	public void setTranslateDao(ITranslateDao translateDao) {
		this.translateDao = translateDao;
	}

	public void setRewriteDao(IRewriteDao rewriteDao) {
		this.rewriteDao = rewriteDao;
	}

	public void setReadDao(IReadingDao readDao) {
		this.readDao = readDao;
	}

	public void setWriteDao(IWritingDao writeDao) {
		this.writeDao = writeDao;
	}

	public void setPassageDao(IPassageDao passageDao) {
		this.passageDao = passageDao;
	}
	@Override
	public String add(MTest model) {
		Test test = new Test();
		FileHandleImpl fileHandle = new FileHandleImpl();
		String path = "../webapps/makeiteasy/listeningMaterials";
		
		String newfileName = fileHandle.saveUploadFile(model.getListenUrl(), path, model.getListenUrlFileName());
		
		test.setListenUrl( "../listeningMaterials/" + newfileName);
		test.setListenUrlFileName(model.getListenUrlFileName());
		
		Teacher teacher = teacherDao.getById(model.getTeaId());
		if (null != teacher) {
			test.setTeacher(teacher);
		}
		
		test.setTestName(model.getTestName());
		test.setTestCreateDate(model.getTestCreateDate());
		return parser(model.getPaperUrl(), test);
	}

	@Override
	public String getById(MTest model) {
		Test test = testDao.getById(model.getTestId());
		if (null == test) {
			throw new ServiceException("ERR-0051");
		}		
		return createTestObj(test).toString();
	}
	
	@Override
	public String getAll(Integer teaId) {
		Teacher teacher = teacherDao.getById(teaId);
		if (null == teacher) {
			throw new ServiceException("ERR-0111");
		}
		List<Test> list = testDao.getListByProperty("teacher.teaId", teacher.getTeaId().toString());
		
		return createTestArr(list).toString();
	}
	
	@Override
	public String deleteById(Integer id) {
		testDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MTest model) {
		
		return "1";
	}


	private JSONObject createTestObj(Test test) {
		JSONObject obj = new JSONObject();
		obj.put("testId", test.getTestId());
		obj.put("listenUrl", test.getListenUrl());
		obj.put("testName", test.getTestName());
		if (null != test.getListen()) {
			ListenImpl listenImpl = new ListenImpl();
			Object listen = listenImpl.createListenObj(test.getListen());
			obj.put("listen", listen);
		}
		if (null != test.getSelection()) {
			SelectionImpl selectionImpl = new SelectionImpl();
			Object selcetion = selectionImpl.createSelectionObj(test.getSelection());
			obj.put("selection", selcetion);
		}
		if (null != test.getTranslate()) {
			TranslateImpl translateImpl = new TranslateImpl();
			Object translate = translateImpl.createTranslateObj(test.getTranslate());
			obj.put("translate", translate);
		}
		if (null != test.getRewrite()) {
			RewriteImpl rewriteImpl = new RewriteImpl();
			Object rewrite = rewriteImpl.createRewriteObj(test.getRewrite());
			obj.put("rewrite", rewrite);
		}
		if (null != test.getReading()) {
			ReadingImpl readingImpl = new ReadingImpl();
			Object read = readingImpl.createReadingObj(test.getReading());
			obj.put("read", read);
		}
		if (null != test.getWriting()) {
			WritingImpl writingImpl = new WritingImpl();
			Object write = writingImpl.createWritingObj(test.getWriting());
			obj.put("write", write);
		}
		return obj;
	}
	
	private JSONArray createTestArr(List<Test> list) {
		JSONArray jarr = new JSONArray();
		if (null != list) {
			for (Test test : list) {
				JSONObject obj = new JSONObject();
				obj.put("testId", test.getTestId());
				obj.put("testName", test.getTestName());
				obj.put("testCreateDate", test.getTestCreateDate().toString().substring(0, 19));
				obj.put("listenUrlFileName", test.getListenUrlFileName());
				if (null != test.getTeacher()) {
					obj.put("teaName", test.getTeacher().getTeaName());
				}
				jarr.add(obj);
			}
		}
		return jarr;
	}
	
	public String parser(File fname, Test test) {
		InputStream fStream = null;
		try {
			fStream = new BufferedInputStream(new FileInputStream(fname));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.print("file can't open");
			return null;
		}

		Scanner scan = new Scanner(fStream);
		String str = scan.nextLine();
		String temp = "";
		String id = "";

		// ///////////////////////////
		Listen listen = new Listen();
		while (!str.matches(".*Part[\\s]+I[.].*") && scan.hasNext()) {
			str = scan.nextLine();
		}

		while (!str.matches(".*Passage.*:.*")) {
			temp += str + " ";
			str = scan.nextLine();
		}

		listen.setListenDirection(temp.replaceAll("\\s+", " "));// listen direction
		temp = "";
		str = "";

		while (!str.matches(".*Key.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		listen.setListenPassge(temp.replaceAll("\\s+", " "));// listen passage
		temp = "";

		while (!str.matches(".*Part[\\s]+II[.].*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		temp = temp.replaceAll("Key.*:", "");
		listen.setListenKeys(temp.replaceAll("\\s+", " "));// listen keys
		temp = "";

		id = listenDao.add(listen);
		listen.setListenId(Integer.parseInt(id));
		test.setListen(listen);// listen

		// ////////////////////////////////////
		Selection selection = new Selection();
		while (!str.matches(".*Passage.*:.*") && scan.hasNext()) {
			temp = str;
			str = scan.nextLine();
		}

		selection.setSelectionDirections(temp.replaceAll("\\s+", " "));// selection direction
		temp = "";
		str = "";

		while (!str.matches(".*Question.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		selection.setSelectionPassge(temp.replace("\\s+", " "));// selection passage
		temp = "";
		str = "";

		while (!str.matches(".*Key.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		selection.setSelections(temp.replace("\\s+", " "));// selection selections
		temp = "";

		while (!str.matches(".*Part[\\s]+III[.].*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		temp = temp.replaceAll("Key.*:", "");
		selection.setSelectionKeys(temp.replace("\\s+", " "));// selection keys
		temp = "";

		id = selectionDao.add(selection);
		selection.setSelectionId(Integer.parseInt(id));
		test.setSelection(selection);// selection

		// ////////////////////////////////////
		Translate translate = new Translate();
		while (!str.matches(".*Question.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		translate.setTranslateDirection(temp.replace("\\s+", " "));// translate direction
		temp = "";
		str = "";

		while (!str.matches(".*Key:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		translate.setTranslateTitle(temp.replaceAll("\\s+", " "));// translate title
		temp = "";

		while (!str.matches(".*Part[\\s]+IV[.].*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		temp = temp.replaceAll("Key.*:", "");
		translate.setTranslateKey(temp.replaceAll("\\s+", " "));// translate keys
		temp = "";

		id = translateDao.add(translate);
		translate.setTranslateId(Integer.parseInt(id));
		test.setTranslate(translate);// translate

		// //////////////////////////////
		Rewrite rewrite = new Rewrite();
		while (!str.matches(".*Question.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		rewrite.setRewriteDirection(temp.replace("\\s+", " "));// rewrite direction
		temp = "";
		str = "";

		while (!str.matches(".*Key:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		rewrite.setRewriteTitle(temp.replaceAll("\\s+", " "));// rewrite title
		temp = "";

		while (!str.matches(".*Part[\\s]+V[.].*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		temp = temp.replaceAll("Key.*:", "");
		rewrite.setRewriteKeys(temp.replaceAll("\\s+", " "));// rewrite keys
		temp = "";

		id = rewriteDao.add(rewrite);
		rewrite.setRewriteId(Integer.parseInt(id));
		test.setRewrite(rewrite);// rewrite

		// //////////////////////////////
		Reading read = new Reading();
		Passage passageI = new Passage();
		Passage passageII = new Passage();
		while (!str.matches(".*Passage[\\s]+I.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		System.out.println(temp.replace("\\s+", " "));
		read.setReadDirection(temp.replace("\\s+", " "));// read direction
		temp = "";
		str = "";

		while (!str.matches(".*Question.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		passageI.setPassageContext(temp.replaceAll("\\s+", " "));
		id = passageDao.add(passageI);
		passageI.setPassageId(Integer.parseInt(id));
		read.setPassageByPassageIid(passageI);// read passage I
		temp = "";
		str = "";

		while (!str.matches(".*Key.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}

		read.setReadI(temp.replaceAll("\\s+", " "));// read I
		temp = "";
		
		while (!str.matches(".*Passage[\\s]+II.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		temp = temp.replaceAll("Key.*:", "");
		read.setReadIkeys(temp.replaceAll("\\s+", " "));// read I keys
		temp = "";
		str = "";
		
		while (!str.matches(".*Question.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		passageII.setPassageContext(temp.replaceAll("\\s+", " "));
		id = passageDao.add(passageII);
		passageII.setPassageId(Integer.parseInt(id));
		read.setPassageByPassageIiid(passageII);// read passage II
		temp = "";
		str = "";
		
		while (!str.matches(".*Key.*:.*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		read.setReadIi(temp.replaceAll("\\s+", " "));// read II
		temp = "";
		
		while (!str.matches(".*Part[\\s]+VI[.].*") && scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		temp = temp.replaceAll("Key.*:", "");
		read.setReadIikeys(temp.replaceAll("\\s+", " "));// read II keys
		temp = "";
		
		id = readDao.add(read);
		read.setReadId(Integer.parseInt(id));
		test.setReading(read);// read
		
		//////////////////////////////
		Writing write = new Writing();
		while (scan.hasNext()) {
			temp += str + " ";
			str = scan.nextLine();
		}
		
		write.setWriteContent(temp.replaceAll("\\s+", " "));// write context
		temp = "";
		
		id = writeDao.add(write);
		write.setWriteId(Integer.parseInt(id));
		test.setWriting(write);// writing
		
		return testDao.add(test);
	}
}
